﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Text;

namespace CNative.Dapper.Utils
{
    public static class JsonHelper
    {
        public static byte[] SerializeObject(object value)
        {
            return UTF8Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));
        }


        public static object DeserializeObject(byte[] value, Type type)
        {
            if (value.Length == 0)
            {
                return null;
            }

            return JsonConvert.DeserializeObject(UTF8Encoding.UTF8.GetString(value), type);
        }

        public static object DeserializeObjectByJson(string value, Type type)
        {
            return JsonConvert.DeserializeObject(value, type);
        }

        public static T DeserializeObjectByJson<T>(string value)
        {
            return (T)DeserializeObjectByJson(value, typeof(T));
        }

        public static string SerializeObjectToJson(object value)
        {
            return JsonConvert.SerializeObject(value);
        }

        public static T DeserializeObject<T>(byte[] value)
        {
            return (T)DeserializeObject(value, typeof(T));
        }


        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToJson(this object value)
        {
            return JsonHelper.SerializeObjectToJson(value);
        }
        /// <summary>
        ///JSON转对象
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(this string value)
        {
            return JsonHelper.DeserializeObjectByJson<T>(value);
        }

        public static string GetExceptionMessage(this Exception exception)
        {
            if (exception == null)
                return string.Empty;

            var message = exception.Message;
            if (exception.InnerException != null)
            {
                message += "|InnerException:" + GetExceptionMessage(exception.InnerException);
            }
            return message;
        }


    }
}
